import { NzMessageService } from 'ng-zorro-antd/message';
import { Tools } from 'src/app/common/tools/tools';
import { Subscription } from 'rxjs';
import { PlaceUseLog } from './../../../../../../models/plactType';
import { ExceptionHandler } from './../../../../../../handler/exception.handler';
import { Place, PlaceType } from 'src/app/models';
import { PlaceService } from './../../../../../../services/place.service';
import { Component, OnInit, OnDestroy, Input } from '@angular/core';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { PlaceUseAxisService } from 'src/app/common/place-use-axis/place-use-axis.service';
import * as dayjs from 'dayjs';

@Component({
  selector: 'zepride-place-select-modal',
  templateUrl: './place-select-modal.component.html',
  styleUrls: ['./place-select-modal.component.less']
})
export class PlaceSelectModalComponent implements OnInit, OnDestroy {
  @Input() useMode: string;
  @Input() useNote: string;

  orgId: string;
  user;
  placeTypeList: PlaceType[] = [];
  placeList: Place[] = [];
  selectedPlaceType: PlaceType;
  selectedPlace: Place;
  initDate: Date[];
  selectedDate: Date[];
  selectedDateRange: Date[];

  resultPlaceUseLogList: PlaceUseLog[] = [];
  selectedFreeFragment: Subscription;

  constructor(
    private psvr: PlaceService,
    private modal: NzModalRef,
    private axisSvr: PlaceUseAxisService,
    private msg: NzMessageService
  ) {
    this.orgId = localStorage.getItem('orgid');
    this.user = JSON.parse(localStorage.getItem('userInfo'));
  }
  ngOnDestroy() {
    if (this.selectedFreeFragment) {
      this.selectedFreeFragment.unsubscribe();
    }
  }

  ngOnInit() {
    this.getPlaceTypes();
    this.selectedFreeFragment = this.axisSvr.selectedFreeFragment$.subscribe(fragment => {
      this.selectedDate = [
        new Date(fragment.fromTime),
        new Date(fragment.toTime)
      ];

      this.selectedDateRange = [
        new Date(fragment.fromTime),
        new Date(fragment.toTime)
      ]
    });
  }

  async getPlaceTypes() {
    try {
      this.placeTypeList = await this.psvr.queryPlaceType({ orgId: this.orgId });
      if (this.placeTypeList.length) {
        this.selectedPlaceType = this.placeTypeList[0];
        this.getPlace();
      }
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }

  async getPlace() {
    try {
      this.placeList = await this.psvr.queryPlace({
        placeTypeId: this.selectedPlaceType.id
      });
      if (this.placeList.length) {
        this.selectedPlace = this.placeList[0];
        this.getPlaceInfo();
      }
      else {
        this.selectedPlace = null;
      }
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }

  async getPlaceInfo() {
    try {
      const placeInfo = await this.psvr.getPlaceById(this.selectedPlace.id);
      this.selectedPlace.placeUseLogs = placeInfo.placeUseLogs;
      this.resultPlaceUseLogList = await this.psvr.queryPlaceUseLogs({
        // placeId: placeInfo.id,
        useObjectType: 'User',
        useObjectId: this.user.id,
        // placeTypeId: this.selectedPlaceType.id
      });

      let begin: number;
      let end: number;

      if (this.initDate && this.initDate.length > 0) {
        const initDateBegin = this.initDate[0].getTime();
        const initDateEnd = this.initDate[1].getTime();

        if (initDateBegin > initDateEnd) {
          throw { message: '开始时间不能大于结束时间！' };
        }

        begin = initDateBegin;
        if (begin < Date.now()) {
          begin = Date.now();
        }
        end = initDateEnd;
      }
      else {
        begin = Date.now();
        end = dayjs(begin).add(1, 'day').valueOf();
      }

      const fragmentList = this.axisSvr.sliceTheTime(placeInfo.placeUseLogs, begin, end);

      this.axisSvr.setDataValue$.next({
        fragmentList,
        begin,
        end
      });
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }

  async onInitDateChange(value: Date[]) {
    await this.getPlaceInfo();
  }

  ok() {
    this.modal.close(this.resultPlaceUseLogList);
  }
  async cancel() {
    for (let item of this.resultPlaceUseLogList) {
      await this.psvr.delPlaceUseLog(item);
    }

    this.modal.close();
  }

  async submitPlaceUseLog() {
    try {
      if (!this.selectedDate || this.selectedDate.length == 0) {
        throw { message: '未选择场地使用时间！' };
      }

      const selectBegin = this.selectedDate[0].getTime();
      const selectEnd = this.selectedDate[1].getTime();

      if (selectBegin > selectEnd) {
        throw { message: '开始时间不能大于结束时间！' };
      }

      if (this.selectedDateRange && this.selectedDateRange.length > 0) {
        const sRangeBegin = this.selectedDateRange[0].getTime();
        const sRangeEnd = this.selectedDateRange[1].getTime();

        if (selectBegin < sRangeBegin || selectEnd > sRangeEnd) {
          throw { message: `所选时间不能超出 [${dayjs(sRangeBegin).format('YYYY-MM-DD HH:mm')}] ~ [${dayjs(sRangeEnd).format('YYYY-MM-DD HH:mm')}]！` };
        }
      }

      if (this.selectedPlace.placeUseLogs.some(x => (x.beginTime < selectBegin && x.endTime > selectBegin) || (x.beginTime < selectEnd && x.endTime > selectEnd))) {
        throw { message: `所选时间已被占用！` };
      }

      let data = new PlaceUseLog();
      data.id = Tools.GetGuid();
      data.placeId = this.selectedPlace.id;
      data.placeName = this.selectedPlace.name;
      data.placeTypeId = this.selectedPlaceType.id;
      data.placeTypeName = this.selectedPlaceType.name;
      data.orgId = this.orgId;
      data.beginTime = selectBegin;
      data.endTime = selectEnd;
      data.useObjectId = this.user.id;
      data.useObjectType = 'User';
      data.useMode = this.useNote;
      data.note = this.useNote;

      await this.psvr.createPlaceUseLog(data);
      this.msg.success('添加成功！');

      await this.getPlaceInfo();
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }

  async delPlaceUseLog(item: PlaceUseLog) {
    try {
      await this.psvr.delPlaceUseLog(item);
      this.msg.success('删除成功！');

      await this.getPlaceInfo();
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }

}
